<?php

!defined('P_W') && exit('Forbidden');
//api mode 1

define('API_USER_USERNAME_NOT_UNIQUE', 100);

class User {

	var $base;
	var $db;

	function User($base) {
		$this->base = $base;
		$this->db = $base->db;
	}

	//获取用户信息
	function getInfo($uids, $fields = array()) {
		if (!$uids) {
			return new ApiResponse(false);
		}

		$uids = is_numeric($uids) ? array($uids) : explode(",",$uids);
		$users = $this->db->from('dbpre_members')->where('uid', $uids)->get_all('uid');
		return new ApiResponse($users);
	}

	//改名
	function alterName($uid, $newname) {
		$newname = trim($newname);
		$member = $this->db->from('dbpre_members')->where('uid', $uid)->get_one();
		$userName = $member['username'];
		if (!$userName || $userName == $newname) {
			return new ApiResponse(1);
		}
		$existUserId = $this->db->from('dbpre_members')->where('username', $newname)->count()>0;
		if ($existUserId) {
			return new ApiResponse(API_USER_USERNAME_NOT_UNIQUE);
		}
		
		//更新主题里的管理员帐号
		$this->db->from('dbpre_members')->where('uid', $uid)->set('username', $newname)->update();
		$subjects = $this->db->from('dbpre_mysubject')->where('uid', $uid)->get_all();
		if($subjects) {
			$sids = array();
			foreach ($subjects as $subject) {
				$sids[] = $subject['sid'];
			}
			if($sids) {
				$this->db->from('dbpre_subject')->where('sid', $sids)->set('username', $newname)->update();
			}
		}
		return new ApiResponse(1);
	}

	//删除用户
	function deluser($uids) {
		foreach (array('members','member_address','member_passport','member_point','member_profile','spaces') as $table) {
			$this->db->from('dbpre_'.$table)->where('uid', $uids)->delete();
		}
		return new ApiResponse(1);
	}

	//同步登录
	function synlogin($user) {
		global $timestamp,$uc_key;
		list($uid, $username, $md5password) = explode("\t", $this->base->strcode($user, false));

		header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR` INT DEM STA PRE COM NAV OTC NOI DSP COR"');

        $cookietime = 31536000;
        $member = $this->db->from('dbpre_members')->where('uid', $uid)->get_one();

        if($member) {
	        $hash = create_formhash($uid, $username, $member['password']);
	        $str = $uid . "\t" . md5($hash);
            set_cookie('hash', authcode($str,'ENCODE'), $cookietime);
        } elseif(!$member) {
            set_cookie('username', $username, $cookietime);
            set_cookie('activation_module', 'pwucenter', $cookietime);
            set_cookie('activationauth', authcode_ex($uid . "\t" . $username), $cookietime);
        }
	}

	//同步登出
	function synlogout() {
		global $_USER;
		header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

		del_cookie(array(
			'uid','hash','username','activationauth',
			'passport_name','passport_id','passport_token_access','passport_expires_in',
		));
	}

	//获取用户组
    function getusergroup() {
        return new ApiResponse(1);
    }
}
?>